package org.richin.date.util;

import java.sql.Timestamp;
import java.util.Date;

import org.apache.commons.beanutils.Converter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.richin.lang.util.StringUtils;

public class DateConverter implements Converter
{
	  private static final Log log = LogFactory.getLog(DateConverter.class);
	  public Object convert(Class arg0, Object value) {
	    String dateStr;
	    try {
	    	if(value instanceof Date){
	    		long time=0;
	    		if(value instanceof java.sql.Date)
	    			time=((java.sql.Date)value).getTime();
	    		else if(value instanceof Timestamp)
	    			time=((Timestamp)value).getTime();
	    		else
	    			time=((Date)value).getTime();
	    		return DateFormatUtils.formatDateToISOString(new Date(time));
	    	}
	      dateStr = (String)value;

	      if (StringUtils.isNotBlank(dateStr))
	        return DateFormatUtils.parseFromFormats(dateStr);
	    }
	    catch (Exception e) {
	      log.error(e.getMessage(), e);
	    }
	    return null;
	  }
}
